/**
 * 解析查询字符串
 * @param str 查询字符串
 * @returns 解析后的对象
 */
export function queryParse(str: string): Record<string, string> {
    if (!str) return {};
    const strParams = decodeURIComponent(str).split('?')[1];
    const paramsObj: Record<string, string> = {};
    strParams.split('&').forEach((item) => {
        const [key, value] = item.split('=');
        paramsObj[key] = value;
    });
    return paramsObj;
}

/**
 * 拼接查询字符串
 * @param path 基础路径
 * @param paramsObj 参数对象
 * @returns 拼接后的完整URL
 */
export function splicingQuery(path: string, paramsObj: Record<string, string | number | undefined> = {}): string {
    const paramsArr = Object.keys(paramsObj);
    if (paramsArr.length === 0) return path;
    
    const queryString = paramsArr
        .filter(key => paramsObj[key] !== undefined)
        .map((key, index) => 
            `${key}=${paramsObj[key] ?? ''}${index !== paramsArr.length - 1 ? '&' : ''}`
        )
        .join('');
    
    return `${path}?${encodeURIComponent(queryString)}`;
}

/**
 * 防抖函数
 * @param method 回调函数
 * @param wait 时间窗口的间隔(毫秒)
 * @param immediate 是否立即执行
 * @returns 防抖处理后的函数
 */
export function debounce<T extends (...args: any[]) => any>(
    method: T,
    wait: number = 300,
    immediate: boolean = false
): (...args: Parameters<T>) => void {
    let timer: ReturnType<typeof setTimeout> | null = null;
    let context: any;
    let args: Parameters<T>;

    const later = () => setTimeout(() => {
        timer = null;
        if (!immediate) {
            method.apply(context, args);
            context = args = null as any;
        }
    }, wait);

    return function (this: any, ...params: Parameters<T>) {
        if (!timer) {
            timer = later();
            if (immediate) {
                method.apply(this, params);
            } else {
                context = this;
                args = params;
            }
        } else {
            clearTimeout(timer);
            timer = later();
        }
    };
}

/**
 * 节流函数
 * @param method 回调函数
 * @param delay 延迟执行时间(毫秒)
 * @param duration 间隔时间(毫秒)
 * @param context 执行上下文
 * @returns 节流处理后的函数
 */
export function throttle<T extends (...args: any[]) => any>(
    method: T,
    delay: number,
    duration: number = 0,
    context: any = null
): (...args: Parameters<T>) => void {
    let timer: ReturnType<typeof setTimeout> | null = null;
    let begin = Date.now();

    return function (this: any, ...args: Parameters<T>) {
        const current = Date.now();
        if (timer) {
            clearTimeout(timer);
        }

        if (duration > 0) {
            if (current - begin > duration) {
                method.apply(context || this, args);
                begin = current;
                return;
            }
        }

        timer = setTimeout(() => {
            method.apply(context || this, args);
        }, delay);
    };
}

/**
 * 获得当前年月日时分秒
 * @returns 格式化的日期时间字符串 (YYYY-MM-DD HH:mm:ss)
 */
export function getCurrentTime(): string {
    const date = new Date();
    const pad = (num: number): string => num.toString().padStart(2, '0');
    
    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1);
    const day = pad(date.getDate());
    const hours = pad(date.getHours());
    const minutes = pad(date.getMinutes());
    const seconds = pad(date.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}